﻿using System.ComponentModel.DataAnnotations.Schema;
using Core.Domain.ValueObjects;

namespace Core.Domain.Entities;

/// <summary>
/// 用户配置文件（聚合根）
/// 管理用户偏好设置集合
/// </summary>
[Table("UserProfiles")]
public class UserProfile : AuditableEntity
{
    public Guid? UserId { get; private init; }

    private readonly List<UserPreference> _preferences = new();

    /// <summary>
    /// 只读访问当前所有偏好项
    /// </summary>
    public IReadOnlyCollection<UserPreference> Preferences => _preferences.AsReadOnly();

    private UserProfile() { } // EF Core 使用

    public UserProfile(Guid userId)
    {
        if (userId == Guid.Empty)
            throw new BoilerplateException("用户不能为空");

        UserId = userId;
    }

    /// <summary>
    /// 设置单个用户偏好（upsert）
    /// </summary>
    public void SetPreference(UserPreference preference)
    {
        if (preference is null)
            throw new ArgumentNullException(nameof(preference));

        preference.Validate();

        var existing = _preferences.FirstOrDefault(p => p.Key == preference.Key);
        if (existing is not null)
            _preferences.Remove(existing);

        _preferences.Add(preference);
    }

    /// <summary>
    /// 获取指定偏好值（若不存在返回默认值）
    /// </summary>
    public T GetPreference<T>(string key, T defaultValue = default!)
    {
        if (string.IsNullOrWhiteSpace(key))
            throw new BoilerplateException("偏好项 Key 不能为空");

        var pref = _preferences.FirstOrDefault(p => p.Key == key);
        return pref is not null ? pref.GetValue<T>() : defaultValue;
    }

    /// <summary>
    /// 批量设置偏好项
    /// </summary>
    public void SetPreferences(IEnumerable<UserPreference> preferences)
    {
        if (preferences is null)
            throw new BoilerplateException(nameof(preferences));

        foreach (var pref in preferences)
            SetPreference(pref);
    }

    /// <summary>
    /// 清除某个偏好项
    /// </summary>
    public void ClearPreference(string key)
    {
        if (string.IsNullOrWhiteSpace(key))
            throw new BoilerplateException("偏好项 Key 不能为空");

        var existing = _preferences.FirstOrDefault(p => p.Key == key);
        if (existing is not null)
            _preferences.Remove(existing);
    }
}
